import React, { memo, useCallback } from 'react'
import { RoomsWrapper } from './style'
import { useSelector, shallowEqual, useDispatch } from 'react-redux'
import RoomItem from '@/components/room-item'
import { useNavigate } from 'react-router-dom'
import { changeDetailInfoAction } from '@/store/modules/detail'

const EntireRooms = memo(() => {
  // 获取 roomList 数据
  const { roomList, totalCount, isLoading } = useSelector((state) => {
    return {
      roomList: state.entire.roomList,
      totalCount: state.entire.totalCount,
      isLoading: state.entire.isLoading,
    }
  }, shallowEqual)

  // 跳转到详情页
  const navigate = useNavigate()
  // 保存到 Redux
  const dispatch = useDispatch()
  const handleItemClick = useCallback(
    (itemData) => {
      console.log(itemData)
      dispatch(changeDetailInfoAction(itemData))
      navigate('/detail')
    },
    [navigate, dispatch]
  )

  return (
    <RoomsWrapper>
      <h2 className="title">共{totalCount}多处住所</h2>
      <div className="list">
        {roomList.map((item) => {
          return <RoomItem itemData={item} itemWidth="20%" key={item._id} itemClick={handleItemClick} />
        })}
      </div>
      {/* 蒙版 */}
      {isLoading && <div className="cover" />}
    </RoomsWrapper>
  )
})

export default EntireRooms
